import argparse
import fcntl
import struct
import socket
from deploy import process
from textwrap import dedent
from deploy import configuration
from deploy.devices.lvm.batch import Batch


class Deploy(object):

    help = "Deploy the Environment from the conf file"

    _help = dedent("""
    Deploy the environment from the conf file.

    Usage:

        super-deploy superx deploy --conf-file [CONF_FILE]

    """)

    def __init__(self, argv):
        self.argv = argv

    def print_help(self):
        return self._help

    def deploy(self, args):
        parser = configuration.load(args.conf_file)
        etcd = parser.get_safe('etcd', 'etcd', None)
        devices = parser.get_safe('superx', 'devices', None)

        import pdb;pdb.set_trace()
        if etcd:
            ips = ''
            # check whether is one of etcd cluster
            command = "ip a |grep \"inet \" |grep -v 127.0.0.1 |awk -F \" \" '{print $2}' |awk -F \"/\" '{print $1}'"
            out, err, code = process.call(command, shell=True)
            for ip in out:
                if ip in etcd:
                    # start etcd service
                    pass
        if devices:
            # batch mkfs bluestore
            
            command = [
                '--devices', devices,
            ]
            Batch(command).main()

    def main(self):
        parser = argparse.ArgumentParser(
            prog='superx-deploy deploy',
            formatter_class=argparse.RawDescriptionHelpFormatter,
            description=self.print_help(),
        )

        parser.add_argument(
            '--conf-file',
            default='/etc/SuperX/deploy.conf',
            help='Give the deploy arguments(defaults to /etc/SuperX/deploy.conf)',
        )

        if len(self.argv) <= 1:
            return parser.print_help()
        args = parser.parse_args(self.argv)
        self.deploy(args)
